<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;

class Goodorder extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];

    //下单
    public function makeorder()
    {
        $good_id = input('good_id');
        $sku_id = input('sku_id');
        $num = input('num');
        $address_id = input('address_id');
        $note = input('note');
        $user = $this->auth->getUser();
        if ($num<=0){
            $this->error('数量不能小于0');
        }
        $address = db('address')
            ->where([
                'id'=>$address_id,
                'user_id'=>$user->id
            ])
            ->find();
        if (!$address){
            $this->error('地址不存在');
        }
        $good = db('products')
            ->where('id',$good_id)
            ->find();
        if (!$good){
            $this->error('商品不存在');
        }
        $sku = db('productssku')
            ->where('id',$sku_id)
            ->find();
        if (!$sku){
            $this->error('商品规格不存在');
        }
        if ($sku['stock'] < $num){
            $this->error('库存不足');
        }
        $ordergood = [
            'name'=>$good['name'],
            'skuname'=>$sku['specificationvalues_names'],
            'image'=>$sku['image'],
            'user_id'=>$user->id,
            'products_id'=>$good_id,
            'productssku_id'=>$sku_id,
            'num'=>$num,
            'price'=>$user->vip_switch?$sku['vip_price']: $sku['price'],
            'countprice'=>($user->vip_switch?$sku['vip_price']: $sku['price'])*$num,
            'createtime'=>time()
        ];


        $order_no = 'good'.date('YmdHis').rand(1000,9999);
        $order = [
            'order_num'=>$order_no,
            'user_id'=>$user->id,
            'note'=>$note,
            'type'=>1,
            'goodprice'=>$ordergood['countprice'],
            'yunfei'=>0,
            'countprice'=>$ordergood['countprice']+0,
            'address'=>json_encode($address,JSON_UNESCAPED_UNICODE),
            'status'=>1,
            'createtime'=>time()
        ];
        $order_id = db('orders')
            ->insertGetId($order);
        $ordergood['order_id'] = $order_id;
        db('ordersgood')
            ->insert($ordergood);
        //下单减少库存
        db('productssku')
            ->where('id',$sku_id)
            ->setDec('stock',$num);
        //增加商品销量
        db('products')
            ->where('id',$good_id)
            ->setInc('sellnum',$num);
        $arr =[
            'user_id'=>$user->id,
            'order_sn'=>$order_no,
            'type'=>2,
            'status'=>1,
            'createtime'=>time()
        ];
        db('userorder')->insert($arr);
        $this->success('下单成功',$order_id);
    }
    //购物车下单
    public function carmakeorder()
    {
        $car_ids = input('car_ids');
        $address_id = input('address_id');
        $note = input('note');
        $user = $this->auth->getUser();
       $address = db('address')
           ->where([
               'id'=>$address_id,
               'user_id'=>$user->id
           ])
           ->find();
       if (!$address){
           $this->error('地址不存在');
       }
        $cars = db('buycar')
            ->where('id','in',$car_ids)
            ->select();
        $ordergood = [];
        $totalprice = 0;
        foreach ($cars as $car){
            $good = db('products')
                ->where('id',$car['products_id'])
                ->find();
            if (!$good){
                $this->error($good['name'].'不存在');
            }
            $sku = db('productssku')
                ->where('id',$car['productssku_id'])
                ->find();
            if (!$sku){
                $this->error($good['name'].' '.$sku['specificationvalues_names'].'不存在');
            }
            if ($sku['stock'] < $car['num']){
                $this->error($good['name'].' '.$sku['specificationvalues_names'].'库存不足');
            }
            $ordergood[] = [
                'name'=>$good['name'],
                'skuname'=>$sku['specificationvalues_names'],
                'image'=>$sku['image'],
                'user_id'=>$user->id,
                'products_id'=>$car['products_id'],
                'productssku_id'=>$car['productssku_id'],
                'num'=>$car['num'],
                'price'=>$user->vip_switch?$sku['vip_price']: $sku['price'],
                'countprice'=>($user->vip_switch?$sku['vip_price']: $sku['price'])*$car['num'],
                'createtime'=>time()
            ];
            $totalprice += ($user->vip_switch?$sku['vip_price']: $sku['price'])*$car['num'];
        }
        $order_no = 'good'.date('YmdHis').rand(1000,9999);
        $order = [
            'order_num'=>$order_no,
            'user_id'=>$user->id,
            'note'=>$note,
            'type'=>1,
            'goodprice'=>$totalprice,
            'yunfei'=>0,
            'countprice'=>$totalprice+0,
           'address'=>json_encode($address,JSON_UNESCAPED_UNICODE),
            'status'=>1,
            'createtime'=>time()
        ];
        //插入订单
        $order_id = db('orders')
            ->insertGetId($order);
        foreach ($ordergood as &$item){
            $item['order_id'] = $order_id;
            //下单减少库存
            db('productssku')
                ->where('id',$item['productssku_id'])
                ->setDec('stock',$item['num']);
            //增加商品销量
            db('products')
                ->where('id',$item['products_id'])
                ->setInc('sellnum',$item['num']);
        }
        //插入订单商品
        db('ordersgood')
            ->insertAll($ordergood);
        //删除购物车
        db('buycar')
            ->where('id','in',$car_ids)
            ->delete();
        $arr =[
            'user_id'=>$user->id,
            'order_sn'=>$order_no,
            'type'=>2,
            'status'=>1,
            'createtime'=>time()
        ];
        db('userorder')->insert($arr);
        $this->success('下单成功',$order_id);
    }
    //余额支付
    public function moneypayorder(){
        $user = $this->auth->getUser();
        $order_id = input('order_id','');
        if(!$order_id){
            $this->error('缺失参数order_id');
        }
        $order = db('orders')->where(['id'=>$order_id])->find();
        $isscore = input('isscore',0);//是否适用积分
        $score = 0;
        $total = $order['total'];
        $usescore = 0;
        if($isscore){
            $scorefee = Config::get('site.scorefee');
            $score = $user->score/$scorefee;
            if($score){
                $total = $order['total']-$score;
                $usescore = $user->score;
            }
        }
        
        if($total>$user->money){
            $this->error('余额不足');
        }
        db('user')->where(['id'=>$user->id])->setDec('money',$total);
        if($score){
            db('user')->where(['id'=>$user->id])->update(['score'=>0]);
            addscorelog($user->id,$user->score,1,'购买普通商品');
        }
        //加记录
        addmoneylog($user->id,$total,1,'购买普通商品');
        db('orders')->where(['id'=>$order_id])->update(['status'=>2,'paytype'=>2,'paytime'=>time(),'usescore'=>$usescore]);
        db('userorder')->where(['order_sn'=>$order['order_num']])->update(['status'=>2]);
        // $this->paysuccess($order_id);
        $this->success('支付成功');
    }
    //订单支付
    public function orderpay()
    {
        // $openid = input('openid')?input('openid'):$this->error('openid未指定');
        $user = $this->auth->getUser();
        $openid = $user->openid;
        $order_id = input('order_id');
        $order = db('orders')
            ->where('id',$order_id)
            ->find();
        if ($order['status'] != 1){
            $this->error('订单状态错误');
        }
        $isscore = input('isscore',0);//是否适用积分
        $score = 0;
        $total = $order['total'];
        $usescore = 0;
        if($isscore){
            $scorefee = Config::get('site.scorefee');
            $score = $user->score/$scorefee;
            if($score){
                $total = $order['total']-$score;
                $usescore = $user->score;
                db('orders')->where(['id'=>$order_id])->update(['usescore'=>$usescore]);
            }
        }
        $out_trade_no = date('YmdHis').'_'.$order_id;
        //更新订单的支付单号
        db('orders')
            ->where('id',$order_id)
            ->update([
                'pay_order_no'=>$out_trade_no
            ]);
        $params = [
            'type'         => 'wechat',
            'orderid' => $out_trade_no,
            'title'        => '购买商品',
            'amount'       => $total,
            'method'       => 'miniapp',
            'openid'       => $openid,
            'notifyurl'    => $this->request->domain().'/api/goodorder/notify/paytype/wechat',
        ];
        // $params['amount'] = 0.01;
        $res =  Service::submitOrder($params);
        $this->success('支付串',$res);
    }
    //订单支付通知
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
            $order = db('orders')
                ->where('pay_order_no',$out_trade_no)
                ->find();
            if ($order && $order['status'] == 1){
                //更新订单状态
                db('orders')
                    ->where('id',$order['id'])
                    ->update([
                        'status'=>2,
                        'paytime'=>time()
                    ]);
                if($order['usescore']){
                    db('user')->where(['id'=>$order['user_id']])->update(['score'=>0]);
                    addscorelog($order['user_id'],$order['usescore'],1,'购买商品');
                }
                db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>2]);
            }


        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    //取消订单
    public function cancelorder()
    {
        $user = $this->auth->getUser();
        $order_id = input('order_id');
        $order = db('orders')
            ->where([
                'id'=>$order_id,
                'user_id'=>$user->id
            ])
            ->find();
        if (!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] != 1){
            $this->error('订单状态错误');
        }
        //更新订单状态
        db('orders')
            ->where('id',$order_id)
            ->update([
                'status'=>5,
                'updatetime'=>time()
            ]);
        //增加库存
        $ordergoods = db('ordersgood')
            ->where('order_id',$order_id)
            ->select();
        foreach ($ordergoods as $ordergood){
            db('productssku')
                ->where('id',$ordergood['productssku_id'])
                ->setInc('stock',$ordergood['num']);
            db('products')
                ->where('id',$ordergood['products_id'])
                ->setDec('sellnum',$ordergood['num']);
        }
        db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>5]);
        $this->success('取消成功');
    }
    //确认收货
    public function confirmorder()
    {
        $user = $this->auth->getUser();
        $order_id = input('order_id');
        $order = db('orders')
            ->where([
                'id'=>$order_id,
                'user_id'=>$user->id
            ])
            ->find();
        if (!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] != 3){
            $this->error('订单状态错误');
        }
        //更新订单状态
        db('orders')
            ->where('id',$order_id)
            ->update([
                'status'=>4,
                'entruetime'=>time()
            ]);
        db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>4]);
        $this->success('确认成功');
    }
    //提醒发货
    public function remindorder()
    {
        $user = $this->auth->getUser();
        $order_id = input('order_id');
        $order = db('orders')
            ->where([
                'id'=>$order_id,
                'user_id'=>$user->id
            ])
            ->find();
        if (!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] != 2){
            $this->error('订单状态错误');
        }
        //更新订单状态
        db('orders')
            ->where('id',$order_id)
            ->update([
                'is_tixing'=>2,
                'updatetime'=>time()
            ]);
        $this->success('提醒成功');
    }

    //根据状态获取订单列表
    public function getorderlist()
    {
        $user = $this->auth->getUser();
        $status = input('status');
        $where = [
            'user_id'=>$user->id
        ];
        if ($status){
            $where['status'] = $status;
        }
        $where['deletetime'] = null;
        $page = input('page',1);
        $limit = input('limit',10);
        $list = db('orders')
            ->where($where)
            ->order('createtime DESC')
            ->page($page,$limit)
            ->select();
        foreach ($list as &$item){
            $item['address'] = json_decode($item['address'],true);
            $item['goods'] = db('ordersgood')
                ->where('order_id',$item['id'])
                ->select();
            //时间格式化
            $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);

            $item['paytime'] = $item['paytime'] ? date('Y-m-d H:i:s',$item['paytime']) :'';
            $item['entruetime'] = $item['entruetime'] ? date('Y-m-d H:i:s',$item['entruetime']):'';
            $item['sendtime'] = $item['sendtime'] ? date('Y-m-d H:i:s',$item['sendtime']):'';
            //订单状态:1=待付款,2=待发货,3=待收货,4=完成,5=已取消
            switch ($item['status']){
                case 1:
                    $item['status_text'] = '待付款';
                    break;
                case 2:
                    $item['status_text'] = '待发货';
                    break;
                case 3:
                    $item['status_text'] = '待收货';
                    break;
                case 4:
                    $item['status_text'] = '完成';
                    break;
                case 5:
                    $item['status_text'] = '已取消';
                    break;
            }
        }
        $this->success('ok',$list);
    }
    //获取订单详情
    public function getorderdetail()
    {
        $user = $this->auth->getUser();
        $order_id = input('order_id');
        $order = db('orders')
            ->where([
                'id'=>$order_id,
                'user_id'=>$user->id
            ])
            ->find();
        if (!$order){
            $this->error('订单不存在');
        }
        $order['address'] = json_decode($order['address'],true);
        $order['goods'] = db('ordersgood')
            ->where('order_id',$order['id'])
            ->select();
        //时间格式化
        $order['createtime'] = date('Y-m-d H:i:s',$order['createtime']);
        $order['paytime'] = $order['paytime'] ? date('Y-m-d H:i:s',$order['paytime']) :'';
        $order['entruetime'] = $order['entruetime'] ? date('Y-m-d H:i:s',$order['entruetime']):'';
        $order['sendtime'] = $order['sendtime'] ? date('Y-m-d H:i:s',$order['sendtime']):'';
        switch ($order['status']){
            case 1:
                $order['status_text'] = '待付款';
                break;
            case 2:
                $order['status_text'] = '待发货';
                break;
            case 3:
                $order['status_text'] = '待收货';
                break;
            case 4:
                $order['status_text'] = '完成';
                break;
            case 5:
                $order['status_text'] = '已取消';
                break;
        }
        $this->success('ok',$order);
    }
    //删除订单
    public function delorder()
    {
        $order_id = input('order_id');
        db('orders')
            ->where('id',$order_id)
            ->update([
                'deletetime'=>time()
            ]);
        $this->success('ok');
    }
}